#!/usr/bin/env python3
import os
import sys
import argparse
import json
from douyin_processor import DouyinProcessor
from dialect_processor import DialectProcessor


def process_specific_videos():
    """Process the specific '相机视野影响鼠标速度' series videos"""
    print("Processing '相机视野影响鼠标速度' series videos...")
    
    # URLs for the specific videos
    url1 = "https://v.douyin.com/i5pkyu9H/"  # This URL needs to be modified based on the actual video 1
    url2 = "https://v.douyin.com/i5pkyu9H/"  # This URL needs to be modified based on the actual video 2
    
    # Create output directory
    output_dir = "gaming_streamer_audio"
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
        
    # Initialize processor
    processor = DouyinProcessor(output_dir)
    
    # Process videos
    video1_segments = processor.process_video(url1, "mouse_speed_series_1")
    video2_segments = processor.process_video(url2, "mouse_speed_series_2")
    
    # Print summary
    if video1_segments:
        print(f"Processed video 1: {len(video1_segments)} segments saved")
    else:
        print("Failed to process video 1")
        
    if video2_segments:
        print(f"Processed video 2: {len(video2_segments)} segments saved")
    else:
        print("Failed to process video 2")
        
    return video1_segments, video2_segments


def create_dialect_streamers_file():
    """Create a template file for dialect streamers with recommendations"""
    print("Creating dialect streamers template file...")
    
    # These are example recommendations for popular dialect streamers
    # In a real application, you would scrape or API-query for popular dialect streamers
    streamers = [
        {
            "name": "东北阿冷",
            "dialect": "东北话",
            "urls": ["https://v.douyin.com/example1/"]
        },
        {
            "name": "广府懒人",
            "dialect": "粤语",
            "urls": ["https://v.douyin.com/example2/"]
        },
        {
            "name": "陕西张老师",
            "dialect": "陕西话",
            "urls": ["https://v.douyin.com/example3/"]
        },
        {
            "name": "四川雨妹",
            "dialect": "四川话",
            "urls": ["https://v.douyin.com/example4/"]
        },
        {
            "name": "上海阿拉小周",
            "dialect": "上海话",
            "urls": ["https://v.douyin.com/example5/"]
        },
        {
            "name": "闽南语小伙",
            "dialect": "闽南话",
            "urls": ["https://v.douyin.com/example6/"]
        },
        {
            "name": "客家姑娘",
            "dialect": "客家话",
            "urls": ["https://v.douyin.com/example7/"]
        },
        {
            "name": "河南方言搞笑",
            "dialect": "河南话",
            "urls": ["https://v.douyin.com/example8/"]
        },
        {
            "name": "山东大叔",
            "dialect": "山东话",
            "urls": ["https://v.douyin.com/example9/"]
        },
        {
            "name": "湖南谢爷",
            "dialect": "湖南话",
            "urls": ["https://v.douyin.com/example10/"]
        },
        {
            "name": "云南小妹",
            "dialect": "云南话",
            "urls": ["https://v.douyin.com/example11/"]
        },
        {
            "name": "贵州山歌",
            "dialect": "贵州话",
            "urls": ["https://v.douyin.com/example12/"]
        },
        {
            "name": "广西壮话",
            "dialect": "广西话",
            "urls": ["https://v.douyin.com/example13/"]
        },
        {
            "name": "北京老炮儿",
            "dialect": "北京话",
            "urls": ["https://v.douyin.com/example14/"]
        },
        {
            "name": "湖北方言",
            "dialect": "湖北话",
            "urls": ["https://v.douyin.com/example15/"]
        },
        {
            "name": "安徽小调",
            "dialect": "安徽话",
            "urls": ["https://v.douyin.com/example16/"]
        },
        {
            "name": "江西老表",
            "dialect": "江西话",
            "urls": ["https://v.douyin.com/example17/"]
        },
        {
            "name": "甘肃方言",
            "dialect": "甘肃话",
            "urls": ["https://v.douyin.com/example18/"]
        },
        {
            "name": "河北老师",
            "dialect": "河北话",
            "urls": ["https://v.douyin.com/example19/"]
        },
        {
            "name": "山西晋语",
            "dialect": "山西话",
            "urls": ["https://v.douyin.com/example20/"]
        }
    ]
    
    # Create output directory
    output_dir = "dialect_audio"
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
        
    # Save the template
    template_file = os.path.join(output_dir, "dialect_streamers_template.json")
    try:
        with open(template_file, 'w', encoding='utf-8') as f:
            json.dump(streamers, f, ensure_ascii=False, indent=2)
        print(f"Created dialect streamers template file at {template_file}")
        
        # Also create a text file with instructions
        instructions_file = os.path.join(output_dir, "README.txt")
        with open(instructions_file, 'w', encoding='utf-8') as f:
            f.write("方言主播音频处理说明\n")
            f.write("====================\n\n")
            f.write("1. 编辑 dialect_streamers_template.json 文件，填入实际的抖音视频链接\n")
            f.write("2. 运行以下命令处理所有方言主播的视频：\n")
            f.write("   python dialect_processor.py --streamers_file dialect_audio/dialect_streamers_template.json\n\n")
            f.write("3. 处理后的音频将保存在 dialect_audio/streamers/ 目录下，每个主播一个子文件夹\n")
            f.write("4. 每个主播将提取5个语音片段，格式为 WAV，48kHz，24位深度，立体声\n\n")
            f.write("注意：\n")
            f.write("- 请确保填入的抖音链接可访问且内容丰富\n")
            f.write("- 所有处理后的音频将是纯人声（去除背景音乐和音效）\n")
            f.write("- 处理过程需要一定时间，取决于视频数量和长度\n")
        
        print(f"Created instructions file at {instructions_file}")
        
    except Exception as e:
        print(f"Error creating template file: {e}")
        
    return template_file


def process_dialect_streamers(streamers_file=None):
    """Process dialect streamers if a file is provided"""
    if not streamers_file:
        print("No streamers file provided, skipping dialect processing")
        return
        
    print(f"Processing dialect streamers from {streamers_file}...")
    processor = DialectProcessor("dialect_audio")
    
    streamers = processor.load_streamers_from_file(streamers_file)
    if streamers:
        results = processor.process_all_streamers(streamers)
        print(f"Processed {len(results)} streamers")
    else:
        print("No streamers found in the file or file could not be loaded")


def main():
    parser = argparse.ArgumentParser(description="Run complete audio processing")
    parser.add_argument("--task", choices=["gaming", "dialect", "both"], default="both", 
                        help="Which task to run: gaming (相机视野影响鼠标速度 series), dialect (streamers), or both")
    parser.add_argument("--streamers_file", help="JSON file with streamers information for dialect task")
    
    args = parser.parse_args()
    
    if args.task in ["gaming", "both"]:
        process_specific_videos()
        
    if args.task in ["dialect", "both"]:
        if args.streamers_file:
            process_dialect_streamers(args.streamers_file)
        else:
            template_file = create_dialect_streamers_file()
            print("\nTo process dialect streamers:")
            print(f"1. Edit {template_file} with actual Douyin URLs")
            print("2. Run this script again with:")
            print(f"   python {sys.argv[0]} --task dialect --streamers_file {template_file}")
    
    print("\nProcessing complete!")


if __name__ == "__main__":
    main() 